/*
============================================================================
FileName	:	XQChatClient.cpp
Author		:	liyake
Website		:	http://www.liyake.com
Create Data	:	2012-03-08 13:07
Change Data	:	2012-03-08 13:07
Detail		:	The socket client of xqchat application
============================================================================
*/

#include "XQChatClient.h"
#include "XQChatRoster.h"
#include "XQChatClientManager.h"
#include <QtGui>

using namespace XQChat;

XQChat::CXQChatClient::CXQChatClient( const CXQChatConfiguration& config )
	: m_config(config)
	, m_pRosterManager(&rosterManager())
{
}

XQChat::CXQChatClient::~CXQChatClient(void)
{

}

void XQChat::CXQChatClient::connectToServer()
{
	QXmppClient::connectToServer(m_config);
	connect(m_pRosterManager,SIGNAL(rosterReceived()),this,SLOT(onRosterReceived()));
	connect(m_pRosterManager,SIGNAL(presenceChanged(const QString&, const QString&)),
		this,SLOT(onPresenceChanged(const QString&, const QString&)));
	connect(m_pRosterManager,SIGNAL(rosterChanged(const QString&)),
		this,SLOT(onRosterChanged(const QString&)));
	connect(m_pRosterManager,SIGNAL(subscriptionReceived(const QString&)),
		this,SLOT(onSubscriptionReceived(const QString&)));
}

void XQChat::CXQChatClient::onRosterReceived()
{
	CXQChatRosterManager* pRosterManager = CXQChatClientManager::getQXChatClientManager()->getRosterManager();

	QStringList listJids = m_pRosterManager->getRosterBareJids();
    foreach(const QString& jid, listJids)
	{
		XQChat::CXQChatRoster* pRoster = new XQChat::CXQChatRoster(jid,this);
		if(!pRosterManager->addRoster(pRoster))
		{
			delete pRoster;
			continue;
		}
	}
	emit rosterReceived();
}

void XQChat::CXQChatClient::onPresenceChanged( const QString& bareJid, const QString& resource )
{
	QXmppPresence presence = m_pRosterManager->getPresence(bareJid,resource);
	CXQChatRosterManager* pRosterManager = CXQChatClientManager::getQXChatClientManager()->getRosterManager();
	QList<CXQChatRoster*> listRosters = pRosterManager->getRostersByBareJid(bareJid);

    foreach(CXQChatRoster* pRoster, listRosters)
	{
		pRoster->setPresence(resource,presence);

		emit presenceChanged(pRoster->getFullJid(),resource);
	}
}

void XQChat::CXQChatClient::onRosterChanged( const QString& bareJid )
{

}

void XQChat::CXQChatClient::onSubscriptionReceived( const QString& bareJid )
{

}
